<template>
  <div class="resource">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline">
          <el-form-item label="资源名称" prop="name" :style="labelWidth">
            <el-input v-model="searchForm.name" clearable placeholder="资源名称"></el-input>
          </el-form-item>
          <el-form-item label="资源路径" prop="url" :style="labelWidth">
            <el-input v-model="searchForm.url" clearable placeholder="资源路径"></el-input>
          </el-form-item>
          <el-form-item label="资源分类" prop="categoryId" :style="labelWidth">
            <el-select v-model="searchForm.categoryId" clearable placeholder="资源分类">
              <el-option
                :label="category.name"
                :value="category.id"
                v-for="category in categories"
                :key="category.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div>
          <el-button @click="resetSearchForm" :disabled="resourceLoading">重置</el-button>
          <el-button type="primary" @click="handleSearch" :disabled="resourceLoading">查询搜索</el-button>
        </div>
      </div>
      <el-card shadow="never" class="operate-container">
        <el-button @click="handleAdd">添加</el-button>
        <el-button @click="resourceCategory">资源分类</el-button>
      </el-card>
      <el-table
        v-loading="resourceLoading"
        :data="resources"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="编号"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="name"
          label="资源名称"
          align="center"
          min-width="150">
        </el-table-column>
        <el-table-column
          prop="url"
          label="资源路径"
          align="center"
          min-width="150">
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          align="center"
          min-width="150">
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="添加时间"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            <span>{{scope.row.createdTime | formatDate}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="searchForm.current"
          :disabled="resourceLoading"
          :page-sizes="[10, 15, 20]"
          :page-size="searchForm.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog :title="handleTitle" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="handleForm">
        <el-form-item label="资源名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="handleForm.name" autocomplete="off" :style="inputWidth"></el-input>
        </el-form-item>
        <el-form-item label="资源路径" prop="name" :label-width="formLabelWidth">
          <el-input v-model="handleForm.url" autocomplete="off" :style="inputWidth"></el-input>
        </el-form-item>
        <el-form-item label="资源分类" prop="name" :label-width="formLabelWidth">
          <el-select v-model="handleForm.categoryId" clearable placeholder="资源分类" :style="inputWidth">
            <el-option
              :label="category.name"
              :value="category.id"
              v-for="category in categories"
              :key="category.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="handleForm.description" autocomplete="off" :style="inputWidth"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="resourceLoading"  @click="saveOrUpdateResource">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Form } from 'element-ui'
import {
  getAllCategory,
  getResourcePages,
  saveOrUpdate,
  deleteResource
} from '@/services/resource'

const ERR_OK = '000000'

interface ResourceItem {
  name: string
  url: string
  categoryId: number | string
  description: string
  id: any
  [key: string]: number | string
}

export default Vue.extend({
  name: 'ResourceIndex',
  data () {
    return {
      isEdit: false,
      searchForm: {
        name: '',
        url: '',
        categoryId: '',
        current: 1,
        size: 15
      },
      resources: [],
      categories: [],
      total: 0,
      resourceLoading: false,
      labelWidth: {
        width: '140px'
      },
      dialogFormVisible: false,
      formLabelWidth: '120px',
      inputWidth: {
        width: '250px'
      },
      handleForm: {
        name: '',
        url: '',
        id: null,
        categoryId: '',
        description: ''
      } as ResourceItem
    }
  },
  computed: {
    handleTitle () {
      return (this as any).isEdit ? '编辑资源' : '新增资源'
    }
  },
  created () {
    this.loadResources()
    this.loadCategory()
  },
  methods: {
    resourceCategory () {
      this.$router.push({
        name: 'resource-category'
      })
    },
    async saveOrUpdateResource () {
      this.resourceLoading = true
      const { data } = await saveOrUpdate(this.handleForm)
      if (data.code === ERR_OK) {
        this.$message.success('添加成功')
      } else {
        this.$message.error('添加失败，请重新添加')
      }
      this.resourceLoading = false
      this.dialogFormVisible = false
      this.loadResources()
    },

    async loadResources () {
      try {
        this.resourceLoading = true
        const { data } = await getResourcePages(this.searchForm)
        if (data.code === ERR_OK) {
          this.resources = data.data.records
          this.total = data.data.total
        }
        this.resourceLoading = false
      } catch (error) {
        this.resourceLoading = false
      }
    },
    async loadCategory () {
      const { data } = await getAllCategory()
      if (data.code === ERR_OK) {
        this.categories = data.data
      }
    },
    resetSearchForm () {
      (this.$refs.searchForm as Form).resetFields()
      this.searchForm.current = 1
      this.loadResources()
    },
    handleSearch () {
      this.searchForm.current = 1
      this.loadResources()
    },
    handleAdd () {
      this.isEdit = false
      this.handleForm = {
        name: '',
        url: '',
        id: null,
        categoryId: '',
        description: ''
      } as ResourceItem
      this.dialogFormVisible = true
    },
    handleEdit (item: ResourceItem) {
      this.isEdit = true
      this.handleForm = item
      this.dialogFormVisible = true
    },
    async handleDelete (row: any) {
      this.$confirm('是否删除该资源?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteResource(row.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(console.log)
    },
    handleSizeChange (val: number) {
      this.searchForm.size = val
      this.searchForm.current = 1
      this.loadResources()
    },
    handleCurrentChange (val: number) {
      this.searchForm.current = val
      this.loadResources()
    }
  }
})
</script>

<style lang="scss" scoped>
.resource {
  .clearfix {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .demo-form-inline {
    margin-top: 15px;
  }
  .pagination-wrapper {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .operate-container {
    width: 100%;
  }
}
</style>
